package com.woniuxy.bookmall.service;

import com.woniuxy.bookmall.entity.*;
import com.woniuxy.bookmall.mapper.TAddressMapper;
import com.woniuxy.bookmall.mapper.TAreaMapper;
import com.woniuxy.bookmall.mapper.TCityMapper;
import com.woniuxy.bookmall.mapper.TProvinceMapper;
import com.woniuxy.bookmall.utils.RedisUtils;
import com.woniuxy.bookmall.vo.AddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class AddressService {

    @Autowired
    RedisUtils redisUtils ;

    @Autowired
    TAddressMapper addressMapper ;

    @Autowired
    TProvinceMapper provinceMapper ;

    @Autowired
    TCityMapper cityMapper ;

    @Autowired
    TAreaMapper areaMapper;

    public List<TAddress> findAddressByUser(TUser user) {
        return addressMapper.selectAddressByUser(user.getId());
    }

    public List<TProvince> getAllProvince() {
        List<TProvince> lists = (List<TProvince>) redisUtils.get("getAllProvince");
        if (lists != null) {
            return lists ;
        }else {
            synchronized (AddressService.class) {
                lists = (List<TProvince>) redisUtils.get("getAllProvince");
                if (lists != null) {
                    return lists ;
                }else {
                    lists = provinceMapper.selectAll();
                    redisUtils.set("getAllProvince",lists);
                    return lists ;
                }
            }
        }
    }

    public List<TCity> getCityByProvince(String code) {
        String key = "getCityByProvince"+code ;
        return cityMapper.selectCityByProvince(code);
    }

    public List<TArea> getAreaByCity(String code) {
        String key = "getAreaByCity"+code ;
        return areaMapper.selectAreaByCity(code);
    }

    public void add(AddressVo addressVo,TUser user) {
        TAddress address = new TAddress();
        address.setDetailaddress(addressVo.getDetailaddress());
        address.setEmailcode(addressVo.getEmailcode());
        address.setIsdefault("0");
        address.setReciver(addressVo.getReciver());
        address.setStatus("1");
        address.setTel(addressVo.getTel());
        String province = provinceMapper.selectProvinceNameByCode(addressVo.getProvince()).getName();
        String city = cityMapper.selectCityNameByCode(addressVo.getCity()).getName();
        String area = areaMapper.selectAreaNameByCode(addressVo.getArea()).getName();
        address.setProvince(province);
        address.setCity(city);
        address.setArea(area);
        address.setUserid(user.getId());

        addressMapper.insert(address);
    }
}
